#include "head.h"

int main(int argc, char *argv[])
{
    // ./client 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");

    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = connect(sockfd,(struct sockaddr *)&serverAddr, sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"connect");

    int epfd = epoll_create(1);
    ERROR_CHECK(epfd,-1,"epoll_create");

    epollAdd(epfd,STDIN_FILENO);
    epollAdd(epfd,sockfd);

    struct epoll_event readySet[5];
    int orderflag;
    while(1)
    {
        printf("> ");
        fflush(stdout);
        
        int readyNum = epoll_wait(epfd,readySet,1,-1);
        for(int i = 0; i < readyNum; ++i)
        {//客户端输入了命令
            if(readySet[i].data.fd == STDIN_FILENO)
            {
                 char buf[1024];
                 ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
                 buf[sret] = '\0';
                 //解析命令
                 char* args;
                 int ret = whichOrder(buf,&orderflag,args);
                 if(ret == 0)
                 {
                    //命令合法，发送请求给服务端
                    transOrder(sockfd,orderflag,args);
                 }
            }
            else
            {//服务端发送了消息
                execOrder_client(orderflag,sockfd);
            }
        }
    }

    close(sockfd);

    return 0;
}

